/********************************************************************
*                                                                   *
* Microsoft Windows Sidebar Gadget for NNTT.ORG                     *
* Released under the MIT license by Alexey Glukharev, Januar 2012.  *
*                                                                   *
********************************************************************/

//----------------------------------------
// CTransmissionDataProvider
//----

// Constructor
CTransmissionDataProvider = function (options) {
    var self = this;
    
    self.g_btRegExp = new RegExp("http:\/\/bt\.nntt\.org\/announce", "i");
    self.g_SessionID = "";
    
    // Опции по умолчанию
    self.g_options = {
        protocol: "",
        host: "",
        port: "",
        user: "",
        password: "",
        error: function (err) {
            System.Debug.outputString("Error occurred: " + err);
        }
    };
    
    // Merge options
    // To keep the correct set of properties we will update only the known properties
    for (var i in self.g_options) {
        if (typeof (options[i]) != 'undefined') {
            self.g_options[i] = options[i];
        }
    }
    
    //----------------------------------------
    // Приватные методы класса
    //----
    self.getResponse = function () {
        var req = {
            'arguments': {
                'fields':[ 'trackers', 'rateUpload', 'rateDownload']
            },
            'method': "torrent-get"
        };
        
        return $.ajax({
            headers: {
                'X-Transmission-Session-Id': self.g_SessionID
            },
            type: 'POST',
            cache: false,
            url: self.g_options.protocol + '://' + self.g_options.host + ':' + self.g_options.port + '/transmission/rpc',
            username: self.g_options.user,
            password: self.g_options.password,
            dataType: 'json',
            contentType: 'application/json',
            data: JSON.stringify(req)
        });
    }
    
    // Фильтрует торренты, принадлежащие nntt
    self.filter = function (trackers) {
        for (var i = 0; i < trackers.length; i++) {
            if (self.g_btRegExp.test(trackers[i].announce))
            return true;
        }
        return false;
    }
    return self;
};

// Methodes
CTransmissionDataProvider.prototype.getData = function (callback) {
    var self = this;
    
    $.when(self.getResponse()).done(function (msg) {
        if (msg.arguments && msg.arguments.torrents) {
            var up = 0;
            var down = 0;
            for (var i = 0; i < msg.arguments.torrents.length; i++) {
                if (self.filter(msg.arguments.torrents[i].trackers)) {
                    up += msg.arguments.torrents[i].rateUpload;
                    down += msg.arguments.torrents[i].rateDownload;
                }
            }
            callback({
                "down": down, "up": up
            });
        }
    })
    .fail(function (request) {
        if (request.status == 409) {
            self.g_SessionID = request.getResponseHeader("X-Transmission-Session-Id");
            self.getData(callback);
        } else {
            self.g_options.error.call();
        }
    });
};